/**
 * Simple Alert Manager
 *
 * 轻量级本地告警管理器，专为本地MCP工具设计
 * 替换过度设计的企业级告警系统
 */

const { getLogger } = require('../logging/logger');

class SimpleAlertManager {
    constructor(configManager) {
        this.configManager = configManager;
        this.logger = getLogger('simple-alert-manager');
        this.alertCount = 0;
        this.lastAlerts = [];
        this.maxLastAlerts = 10;
        this.initialized = false;
    }

    /**
     * 初始化告警管理器
     */
    initialize() {
        if (this.initialized) {
            return;
        }

        this.logger.info('Simple Alert Manager initialized');
        this.initialized = true;
    }

    /**
     * 记录错误告警
     * @param {string} message - 错误消息
     * @param {Error} error - 错误对象
     * @param {Object} context - 上下文信息
     */
    logError(message, error = null, context = {}) {
        this.alertCount++;

        const alertInfo = {
            type: 'error',
            message,
            timestamp: new Date().toISOString(),
            count: this.alertCount
        };

        if (error) {
            alertInfo.error = {
                name: error.name,
                message: error.message,
                code: error.code || 'UNKNOWN_ERROR'
            };
        }

        if (Object.keys(context).length > 0) {
            alertInfo.context = context;
        }

        this.addToLastAlerts(alertInfo);
        this.logger.error(`ALERT #${this.alertCount}: ${message}`, alertInfo);
    }

    /**
     * 记录警告告警
     * @param {string} message - 警告消息
     * @param {Object} context - 上下文信息
     */
    logWarning(message, context = {}) {
        this.alertCount++;

        const alertInfo = {
            type: 'warning',
            message,
            timestamp: new Date().toISOString(),
            count: this.alertCount
        };

        if (Object.keys(context).length > 0) {
            alertInfo.context = context;
        }

        this.addToLastAlerts(alertInfo);
        this.logger.warn(`ALERT #${this.alertCount}: ${message}`, alertInfo);
    }

    /**
     * 记录信息告警
     * @param {string} message - 信息消息
     * @param {Object} context - 上下文信息
     */
    logInfo(message, context = {}) {
        this.alertCount++;

        const alertInfo = {
            type: 'info',
            message,
            timestamp: new Date().toISOString(),
            count: this.alertCount
        };

        if (Object.keys(context).length > 0) {
            alertInfo.context = context;
        }

        this.addToLastAlerts(alertInfo);
        this.logger.info(`ALERT #${this.alertCount}: ${message}`, alertInfo);
    }

    /**
     * 添加到最近告警列表
     * @param {Object} alertInfo - 告警信息
     */
    addToLastAlerts(alertInfo) {
        this.lastAlerts.push(alertInfo);
        if (this.lastAlerts.length > this.maxLastAlerts) {
            this.lastAlerts.shift();
        }
    }

    /**
     * 获取告警统计信息
     * @returns {Object} 统计信息
     */
    getStats() {
        const stats = {
            totalAlerts: this.alertCount,
            recentAlerts: this.lastAlerts.length,
            lastAlert: null
        };

        if (this.lastAlerts.length > 0) {
            stats.lastAlert = this.lastAlerts[this.lastAlerts.length - 1];
        }

        // 按类型统计最近告警
        const typeCount = {
            error: 0,
            warning: 0,
            info: 0
        };

        this.lastAlerts.forEach(alert => {
            if (typeCount[alert.type] !== undefined) {
                typeCount[alert.type]++;
            }
        });

        stats.recentByType = typeCount;
        return stats;
    }

    /**
     * 获取最近的告警列表
     * @param {number} limit - 限制数量
     * @returns {Array} 告警列表
     */
    getRecentAlerts(limit = 10) {
        return this.lastAlerts.slice(-limit);
    }

    /**
     * 检查系统健康状态
     * @param {Object} metrics - 系统指标
     * @returns {Object} 健康状态
     */
    checkHealth(metrics = {}) {
        const health = {
            status: 'healthy',
            issues: [],
            timestamp: new Date().toISOString()
        };

        // 检查内存使用率
        if (metrics.memoryUsagePercent && metrics.memoryUsagePercent > 90) {
            health.status = 'critical';
            health.issues.push({
                type: 'high_memory',
                message: `内存使用率过高: ${metrics.memoryUsagePercent}%`,
                severity: 'critical'
            });
        } else if (metrics.memoryUsagePercent && metrics.memoryUsagePercent > 80) {
            if (health.status === 'healthy') {
                health.status = 'warning';
            }
            health.issues.push({
                type: 'high_memory',
                message: `内存使用率较高: ${metrics.memoryUsagePercent}%`,
                severity: 'warning'
            });
        }

        // 检查错误率
        if (metrics.errorRate && metrics.errorRate > 10) {
            health.status = 'critical';
            health.issues.push({
                type: 'high_error_rate',
                message: `错误率过高: ${metrics.errorRate}%`,
                severity: 'critical'
            });
        } else if (metrics.errorRate && metrics.errorRate > 5) {
            if (health.status === 'healthy') {
                health.status = 'warning';
            }
            health.issues.push({
                type: 'high_error_rate',
                message: `错误率较高: ${metrics.errorRate}%`,
                severity: 'warning'
            });
        }

        // 检查响应时间
        if (metrics.avgResponseTime && metrics.avgResponseTime > 2000) {
            if (health.status === 'healthy') {
                health.status = 'warning';
            }
            health.issues.push({
                type: 'slow_response',
                message: `响应时间较慢: ${metrics.avgResponseTime}ms`,
                severity: 'warning'
            });
        }

        return health;
    }

    /**
     * 清除告警历史
     */
    clearHistory() {
        this.lastAlerts = [];
        this.alertCount = 0;
        this.logger.info('Alert history cleared');
    }

    /**
     * 停止告警管理器
     */
    stop() {
        if (this.initialized) {
            this.logger.info(`Simple Alert Manager stopped. Total alerts handled: ${this.alertCount}`);
            this.initialized = false;
        }
    }
}

module.exports = SimpleAlertManager;